package com.dream.dao.impl;

import com.dream.dao.ClazzDao;
import com.dream.pojo.Clazz;
import com.dream.utils.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class ClazzDaoImpl implements ClazzDao {
    @Override
    public List<Clazz> findClazzByMajorId(String majorId) {
        return DBUtil.commonQuery(Clazz.class,"select * from clazz where major_id=?",majorId);
    }

    @Override
    public long totalCount(String clazzName) {
        String sql = "select count(clazz.clazz_id) from clazz where 1=1";
        StringBuilder sb = new StringBuilder(sql);
        if (clazzName!=null&&!"".equals(clazzName)){
            sb.append("and clazz.clazz_name like '%"+clazzName+"%'");
        }
        return DBUtil.queryCount(sb.toString());
    }

    @Override
    public List<Clazz> list(String clazzName, long pageIndex, long pageSize) {
        String sql = "select * FROM clazz where 1=1";

        StringBuilder sb = new StringBuilder(sql);
        if (clazzName != null && !"".equals(clazzName)) {
            sb.append(" and clazz.clazz_name like '%" + clazzName + "%'");
        }
        sb.append(" limit ?,?");
        return DBUtil.commonQuery(Clazz.class, sb.toString(), (pageIndex - 1) * pageSize, pageSize);
    }

    @Override
    public int add(Clazz clazz) {
        try {
            DBUtil.commonUpdate("insert into clazz values (?,?,?,?)",
                    clazz.getClazzId(),
                    clazz.getMajorId(),
                    clazz.getClazzName(),
                    clazz.getRemark());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Clazz findById(String clazzId) {
        ArrayList<Clazz> list = DBUtil.commonQuery(Clazz.class, "select * from clazz where clazz_id=?", clazzId);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public int update(Clazz clazz) {
        try {
            DBUtil.commonUpdate("update clazz set clazz_name=?,remark=?,major_id=? where clazz_id=?",
                    clazz.getClazzName(),
                    clazz.getRemark(),
                    clazz.getMajorId(),
                    clazz.getClazzId());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteById(String clazzId) {
        try {
            DBUtil.commonUpdate("delete from  clazz where clazz_id=?", clazzId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
